//
//  TLRechargeViewController.m
//  WXReader
//
//  Created by huaya on 2025/1/15.
//  Copyright © 2025 Andrew. All rights reserved.
//

#import "TLRechargeViewController.h"
#import "TLRechargeCollectionViewCell.h"
#import "TLRechargeGoodsModel.h"
#import "TL_WebViewViewController.h"

#import "DJAppRestorAlterView.h"

@interface TLRechargeViewController ()<UIScrollViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource>
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIView *navView;
@property (nonatomic, strong) UIView *headView;
@property (nonatomic, strong) UIView *headBgView;
@property (nonatomic, strong) UIView *headBgBView;
@property (nonatomic, strong) UIButton *restoreBtn;
@property (nonatomic, strong) UIImageView *headVipImgView;
@property (nonatomic, strong) UILabel *headTitleLab;
@property (nonatomic, strong) UILabel *headTipsLab;
@property (nonatomic, strong) UILabel *headExLab;
@property (nonatomic, strong) UILabel *headExDateLab;
@property (nonatomic, strong) UIImageView *headBottomImgView;

@property (nonatomic, strong) UIView *goodsView;
@property (nonatomic, strong) UIButton *checkBtn;
@property (nonatomic, strong) YYLabel *checkLab;

@property (nonatomic, strong) UIView *chooseView;
@property (nonatomic, strong) UIView *fgView;

@property (nonatomic, strong) UILabel *titleLab;
@property (nonatomic, strong) UILabel *contentLab;

@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) UILabel *priceLab;
@property (nonatomic, strong) UIButton *rechargeBtn;

@property (nonatomic, strong) UIButton *backBtn;
@property (nonatomic, strong) UILabel *navTitleLab;

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, strong) TLRechargeGoodsModel *selectedModel;
@end

@implementation TLRechargeViewController
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}
- (NSMutableArray *)dataArr{
    if (!_dataArr) {
        _dataArr = [NSMutableArray new];
    }
    return _dataArr;
}
- (UICollectionView *)collectionView{
    if (!_collectionView) {
        
        // 创建 UICollectionViewFlowLayout
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        
        // 设置两列，行间距和列间距
        CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
        layout.itemSize = CGSizeMake((screenWidth - 17 * 2 - 13) / 2, 120);  // 两列，屏幕两边17，列间距13
        layout.minimumLineSpacing = 15; // 行间距
        layout.minimumInteritemSpacing = 13; // 列间距
        layout.sectionInset = UIEdgeInsetsMake(0, 17, 0, 17); // 左右边距17
        layout.sectionHeadersPinToVisibleBounds = NO;
        // 初始化 UICollectionView
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.bounces = NO;
        _collectionView.scrollEnabled = NO;
        // 注册 NIB 文件
        [_collectionView registerNib:[UINib nibWithNibName:@"TLRechargeCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"TLRechargeCollectionViewCell"];
        
        // 设置背景色
        _collectionView.backgroundColor = [UIColor whiteColor];
        
    }
    return _collectionView;
}
- (void)backAction{
    if (self.navigationController) {
        // 如果导航控制器本身是被 present 的，则 dismiss 整个导航控制器
        if (self.navigationController.presentingViewController) {
            [self dismissViewControllerAnimated:YES completion:nil];
        }
        // 否则，执行 pop
        else {
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
    // 没有导航控制器，直接 dismiss
    else if (self.presentingViewController) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}
- (UIView *)navView{
    if (!_navView) {
        _navView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, PUB_NAVBAR_HEIGHT)];
        [_navView setBackgroundColor:[UIColor whiteColor]];
        _backBtn = [[UIButton alloc] initWithFrame:CGRectMake(6, PUB_NAVBAR_HEIGHT - 28 - 6, 28, 28)];
        [_backBtn setImage:[UIImage imageNamed:@"tzxqy_fh"] forState:UIControlStateNormal];
        [_backBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
        
        [_navView addSubview:_backBtn];
        
        _restoreBtn = [[UIButton alloc] initWithFrame:CGRectMake(kScreenWidth-16-130, PUB_NAVBAR_HEIGHT - 28, 130, 14)];
        [_restoreBtn setTitle:@"Restore Purchases" forState:UIControlStateNormal];
        [_restoreBtn setTitleColor:[UIColor colorWithHexString:@"#956100"] forState:UIControlStateNormal];
        _restoreBtn.titleLabel.font = MK_FONT_PFSC_Medium(14);
        [_restoreBtn addTarget:self action:@selector(restoreAction) forControlEvents:UIControlEventTouchUpInside];
        [_navView addSubview:_restoreBtn];
        
        
        
        _navTitleLab = [[UILabel alloc] initWithFrame:CGRectMake(0, PUB_NAVBAR_HEIGHT - 28 - 6, kScreenWidth, 28)];
        _navTitleLab.text = @"SVIP";
        _navTitleLab.textColor = [UIColor colorWithHexString:@"#000000"];
        _navTitleLab.font = [UIFont systemFontOfSize:17 weight:UIFontWeightMedium];
        _navTitleLab.textAlignment = NSTextAlignmentCenter;
        [_navView addSubview:_navTitleLab];
        
        _navView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0];
        _navTitleLab.textColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0];
    }
    return _navView;
}

- (UIView *)bottomView{
    if (!_bottomView) {
        _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT-46-MK_SCREEN_SAVE_BOTTOM_HEIGHT, kScreenHeight, 46+MK_SCREEN_SAVE_BOTTOM_HEIGHT)];
        [_bottomView setBackgroundColor:[UIColor whiteColor]];
        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 1)];
        [lineView setBackgroundColor:[UIColor colorWithHexString:@"#F1F1F1"]];
        [_bottomView addSubview:lineView];
        
        UILabel *titleLab = [[UILabel alloc] initWithFrame:CGRectMake(17, 13, 50, 22)];
        titleLab.text = @"Total:";
        titleLab.textColor = [UIColor colorWithHexString:@"#333333"];
        titleLab.font = [UIFont systemFontOfSize:16 weight:UIFontWeightMedium];
        [_bottomView addSubview:titleLab];
        [titleLab sizeToFit];
        
        UILabel *priceLab = [[UILabel alloc] initWithFrame:CGRectMake(10+CGRectGetMaxX(titleLab.frame), 13, 50, 22)];
        priceLab.text = @"$ 0";
        priceLab.textColor = [UIColor colorWithHexString:@"#9E6DFC"];
        priceLab.font = [UIFont systemFontOfSize:18 weight:UIFontWeightBold];
        [_bottomView addSubview:priceLab];
        [priceLab sizeToFit];
        self.priceLab = priceLab;
        
        UIButton *rechargeBtn = [[UIButton alloc] initWithFrame:CGRectMake(kScreenWidth-124, 0, 124, 46)];
        [rechargeBtn setBackgroundColor:[UIColor colorWithHexString:@"#9E6DFC"]];
        [rechargeBtn setTitle:@"Recharge" forState:UIControlStateNormal];
        [rechargeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        rechargeBtn.titleLabel.font = [UIFont systemFontOfSize:18 weight:UIFontWeightBold];
        [rechargeBtn addTarget:self action:@selector(rechargeAction) forControlEvents:UIControlEventTouchUpInside];
        [_bottomView addSubview:rechargeBtn];
        
    }
    return _bottomView;
}
- (void)rechargeAction{
    
    if (!self.selectedModel) {
        return;
    }
    if (!self.checkBtn.selected) {
        [kMainWindow showTextHUD:@"You need to read and agree to the relevant agreement" afterDelay:2];
        return;
    }
    
    if (!TL_UserInfoManager.isLogin) {
        
        DJAppRestorAlterView *alterView = [DJAppRestorAlterView createViewWithType:@"0"];
        
        [alterView showAction];
        alterView.ykBlock = ^{
            //调用用户信息接口
            [TL_UtilsHelper guestAuthLoginAction:^(TL_UserInfoModel * _Nonnull userInfo) {
                [self refreshUI];
                [self rechargeAction];
            }];
        };
        
        alterView.loginBlock = ^{
            [TL_LoginViewController presentLoginView:^(TL_UserInfoModel * _Nonnull userDataModel) {
                [self refreshUI];
                [self rechargeAction];
            }];
        };
        
        alterView.reloadDataBlock = ^{
            
            [self refreshData];
        };
        
        return;
    }
    
    [[MKApplePayUtils sharedInstance] createOrderWithItem:self.selectedModel novelId:nil videoId:nil andIsAuto:NO];
    
}
- (UILabel *)contentLab{
    if (!_contentLab) {
        _contentLab = [[UILabel alloc] initWithFrame:CGRectMake(17, CGRectGetMaxY(self.titleLab.frame)+10, kScreenWidth-17*2, 240)];
        
//        _contentLab.text = @"1. When you recharge SVIP, the system will automatically convert the curreof your region for payment；\r\n2. SVIP is a virtual commodity. Once it's recharged, it's non-refundable;\r\n3. After recharging SVIP,you can read all the stories in the SVIP section during the validity period;\r\n4. If the account is not available for a long time after recharging SVIP, lease click here to contact us. We will follow up and help you;\r\n5. Working time: Monday to Friday, 10 AM - 10 PM";
        
        _contentLab.text = @"1. During your VIP subscription, enjoy unlimited access to all TainTale stories.\r\n2. Multiple subscription plans are available, with pricing adjusted for your country / region.\r\n3. VIP is a non-refundable digital product.\r\n4. For support, contact us via Help Center (Profile > Help Center).";
        _contentLab.textColor = [UIColor colorWithHexString:@"#999999"];
        _contentLab.font = [UIFont systemFontOfSize:14 weight:UIFontWeightMedium];
        _contentLab.numberOfLines = 0;
    }
    return _contentLab;
}
- (UILabel *)titleLab{
    if (!_titleLab) {
        _titleLab = [[UILabel alloc] initWithFrame:CGRectMake(17, CGRectGetMaxY(self.fgView.frame)+13, 300, 25)];
        _titleLab.text = @"Tips";
        _titleLab.textColor = [UIColor colorWithHexString:@"#333333"];
        _titleLab.font = [UIFont systemFontOfSize:18 weight:UIFontWeightBold];
    }
    return _titleLab;
}
- (UIView *)fgView{
    if (!_fgView) {
        _fgView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.chooseView.frame)+10, kScreenWidth, 10)];
        [_fgView setBackgroundColor:[UIColor colorWithHexString:@"#F9F9F9"]];
        
    }
    return _fgView;
}
- (UIView *)chooseView{
    if (!_chooseView) {
        _chooseView = [[UIView alloc] initWithFrame:CGRectMake(16, CGRectGetMaxY(self.checkLab.frame)+11, kScreenWidth-16*2, 95)];
        _chooseView.layer.masksToBounds = YES;
        _chooseView.layer.cornerRadius = 6;
        _chooseView.layer.borderWidth = 1;
        _chooseView.layer.borderColor = [UIColor colorWithHexString:@"#F0EEF5"].CGColor;
        
        UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(13, 5, _chooseView.size.width-26, 22)];
        lab.text = @"Payment method";
        lab.textColor = [UIColor colorWithHexString:@"#333333"];
        lab.font = [UIFont systemFontOfSize:16 weight:UIFontWeightMedium];
        lab.numberOfLines = 0;
        [_chooseView addSubview:lab];
        
        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(lab.frame)+5, _chooseView.frame.size.width, 1)];
        [lineView setBackgroundColor:[UIColor colorWithHexString:@"#F0EEF5"]];
        [_chooseView addSubview:lineView];
        
        UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(10, CGRectGetMaxY(lineView.frame)+15, 83, 32)];
        [imgView setImage:[UIImage imageNamed:@"apple pay"]];
        [_chooseView addSubview:imgView];
        
        UIButton *payBtn = [[UIButton alloc] initWithFrame:CGRectMake(_chooseView.frame.size.width-16-18, CGRectGetMaxY(lineView.frame)+22, 18, 18)];
        [payBtn setImage:[UIImage imageNamed:@"hy_xz"] forState:UIControlStateNormal];
        [_chooseView addSubview:payBtn];
        
    }
    return _chooseView;
}
- (YYLabel *)checkLab{
    if (!_checkLab) {
        _checkLab = [[YYLabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.checkBtn.frame)+10, CGRectGetMinY(self.checkBtn.frame), 300, 34)];
//        _checkLab.text = @"I have read and agree to the《User Agreement》and《Privacy Agreement》";
        _checkLab.textColor = [UIColor colorWithHexString:@"#666666"];
        _checkLab.font = [UIFont systemFontOfSize:12 weight:UIFontWeightMedium];
        _checkLab.numberOfLines = 0;
        _checkLab.textAlignment = NSTextAlignmentLeft;
        
        NSString *prefix = @"I have read and agree to the ";
        NSString *userProtocol = [NSString stringWithFormat:@"《%@》", WXLocalizedString(@"用户协议")];
        NSString *privacyProtocl = [NSString stringWithFormat:@"《%@》", WXLocalizedString(@"隐私政策")];
        
        
        NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"I have read and agree to the %@ and %@", userProtocol, privacyProtocl] attributes:@{NSFontAttributeName : _checkLab.font, NSForegroundColorAttributeName : _checkLab.textColor}];
        text.lineSpacing = kQuarterMargin;
        text.alignment = NSTextAlignmentLeft;

        NSRange userProtocolRange = NSMakeRange(prefix.length, userProtocol.length);
        NSRange privacyProtoclRange = NSMakeRange(NSMaxRange(userProtocolRange)+5, privacyProtocl.length);
        
        MK_WEAK_SELF;

        [text setTextHighlightRange:userProtocolRange color:kMainColor backgroundColor:[UIColor clearColor] tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {

            TL_WebViewViewController *vc = [[TL_WebViewViewController alloc] init];
            vc.isPresentState = NO;
            vc.navTitle = WXLocalizedString(@"用户协议");
            vc.URLString = [NSString stringWithFormat:@"%@",[APIURLManager AgreementURL]];
            [weakSelf.navigationController pushViewController:vc animated:YES];
        }];
        [text setTextHighlightRange:privacyProtoclRange color:kMainColor backgroundColor:[UIColor clearColor] tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {

            TL_WebViewViewController *vc = [[TL_WebViewViewController alloc] init];
            vc.isPresentState = NO;
            vc.navTitle = WXLocalizedString(@"隐私政策");
            vc.URLString = [NSString stringWithFormat:@"%@",[APIURLManager PrivacyURL]];
            [weakSelf.navigationController pushViewController:vc animated:YES];
        }];

        _checkLab.attributedText = text;
        
    }
    return _checkLab;
}
- (void)checkAction:(UIButton *)btn{
    btn.selected = !btn.selected;
    
}
- (UIButton *)checkBtn{
    if (!_checkBtn) {
        _checkBtn = [[UIButton alloc] initWithFrame:CGRectMake(18, CGRectGetMaxY(self.goodsView.frame)+12, 18, 18)];
        [_checkBtn setImage:[UIImage imageNamed:@"re_check"] forState:UIControlStateNormal];
        [_checkBtn setImage:[UIImage imageNamed:@"hy_xz"] forState:UIControlStateSelected];
        [_checkBtn addTarget:self action:@selector(checkAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _checkBtn;
}
- (UIView *)goodsView{
    if (!_goodsView) {
        _goodsView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.headView.frame), kScreenWidth, 300)];
        [_goodsView setBackgroundColor:[UIColor blueColor]];
    }
    return _goodsView;
}
- (UIView *)headView{
    if (!_headView) {
        _headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 230)];
        
        _headBgView = [[UIView alloc] init];
        [_headView addSubview:_headBgView];
        [_headBgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(_headView);
        }];
        
        _headBgBView = [[UIView alloc] init];
        [_headBgView addSubview:_headBgBView];
        [_headBgBView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_headBgView.mas_top).offset(100);
            make.left.equalTo(_headBgView.mas_left).offset(16);
            make.right.equalTo(_headBgView.mas_right).offset(-16);
            make.bottom.equalTo(_headBgView);
        }];
        
        _headVipImgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"hy_bs"]];
        [_headBgBView addSubview:_headVipImgView];
        [_headVipImgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(30, 24));
            make.top.equalTo(_headBgBView.mas_top).offset(20);
            make.left.equalTo(_headBgBView.mas_left).offset(23);
        }];
        
        _headBottomImgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Subtract"]];
        [_headView addSubview:_headBottomImgView];
        [_headBottomImgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(_headView);
            make.height.offset(20);
        }];
        
        _headTitleLab = [[UILabel alloc] init];
        _headTitleLab.text = @"VIP Membership";
        _headTitleLab.textColor = [UIColor colorWithHexString:@"#9E6DFC"];
        _headTitleLab.font = [UIFont systemFontOfSize:28 weight:UIFontWeightHeavy];
        [_headBgBView addSubview:_headTitleLab];
        [_headTitleLab mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.centerY.equalTo(_headVipImgView.mas_centerY);
            make.left.equalTo(_headVipImgView.mas_right).offset(8);
            
        }];
        _headTipsLab = [[UILabel alloc] init];
        _headTipsLab.text = @"Unlimited Access to All Stories";
        _headTipsLab.textColor = [UIColor colorWithHexString:@"#9E6DFC"];
        _headTipsLab.font = [UIFont systemFontOfSize:14 weight:UIFontWeightBold];
        [_headBgBView addSubview:_headTipsLab];
        [_headTipsLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_headVipImgView.mas_bottom).offset(10);
            make.left.equalTo(_headBgBView.mas_left).offset(23);
            make.height.offset(14);
        }];
        
        _headExLab = [[UILabel alloc] init];
        _headExLab.text = @"Expiration date：";
        _headExLab.textColor = [UIColor colorWithHexString:@"#9E6DFC"];
        _headExLab.font = [UIFont systemFontOfSize:12 weight:UIFontWeightBold];
        [_headBgBView addSubview:_headExLab];
        [_headExLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_headTipsLab.mas_bottom).offset(10);
            make.left.equalTo(_headBgBView.mas_left).offset(23);
            make.height.offset(14);
        }];
        
        _headExDateLab = [[UILabel alloc] init];
        _headExDateLab.text = @"2024-01-10";
        _headExDateLab.textColor = [UIColor colorWithHexString:@"#9E6DFC"];
        _headExDateLab.font = [UIFont systemFontOfSize:12 weight:UIFontWeightBold];
        [_headBgBView addSubview:_headExDateLab];
        [_headExDateLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_headExLab.mas_bottom).offset(3);
            make.left.equalTo(_headBgBView.mas_left).offset(23);
            make.height.offset(14);
        }];
        
    }
    return _headView;
}
- (UIScrollView *)scrollView{
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
        _scrollView.delegate = self;
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.bounces = NO;  // 关闭所有方向的弹性效果
        _scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        _scrollView.decelerationRate = UIScrollViewDecelerationRateFast; // 快速停止，减少滑动惯性
        [_scrollView setContentSize:CGSizeMake(0, SCREEN_HEIGHT*2)];
    }
    return _scrollView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.view setBackgroundColor:[UIColor whiteColor]];

    [self setupUI];
    [self netWork];
    
    if(TL_UserInfoManager.isLogin){
        [self refreshUI];
    }else{
        _headExLab.text = @"You are not a member yet";
        _headExDateLab.text = @"";
    }
    
    [MKApplePayUtils sharedInstance].completeTransactionBlock = ^{
        [self refreshData];
    };
}
- (void)refreshData{

    [APIManager sendGetRequest:[APIURLManager getUserInfo] parameters:nil model:nil success:^(BOOL success, id  _Nullable responseData, APIResponse * _Nonnull requestModel) {
        
        if (success) {
            
            TL_UserInfoModel *usermodel = [TL_UserInfoModel mj_objectWithKeyValues:requestModel.data[@"userInfo"]];

            NSDictionary *userDataDict = [usermodel mj_keyValues];
            
            [[NSUserDefaults standardUserDefaults] setObject:userDataDict forKey:@"UserInfoModelDict"];
            
            TL_UserInfoManager.updateWithDict(requestModel.data[@"userInfo"]);
            
            [self refreshUI];
            
        } else {
            [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeError alertTitle:requestModel.msg ?: WXLocalizedString(@"请求失败")];
            if (requestModel.code == 302) {
                [TL_UserInfoManager logout];
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        NSLog(@"23");
    }];
}
- (void)setupUI{
    
    [self.view addSubview:self.scrollView];
    
    [self.view addSubview:self.navView];
    
    [self.scrollView addSubview:self.headView];
    
    [self.view layoutIfNeeded];
    [_headBgBView addRoundingCornersWithRoundingCorners:UIRectCornerTopLeft|UIRectCornerTopRight andCornerRadii:10];
    
//    [self customInitialization:_headBgBView andLeftColorHex:@"#E8E9FB" andRightColorHex:@"#E8E9FB" andCornerRadius:0];
    
    [_headBgBView setBackgroundColor:[UIColor colorWithHexString:@"#E8E9FB"]];
    
    [self customInitialization:_headBgView andLeftColorHex:@"CEB5FD" andRightColorHex:@"#B28AFD" andCornerRadius:0];
    
    [self.scrollView addSubview:self.goodsView];
    [self.goodsView addSubview:self.collectionView];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.goodsView);
    }];
    
    
    [self.view addSubview:self.bottomView];
}
- (void)setupUITwo{
    
    [self.scrollView addSubview:self.checkBtn];
    
    [self.scrollView addSubview:self.checkLab];
    
    [self.scrollView addSubview:self.chooseView];
    
    [self.scrollView addSubview:self.fgView];
    
    [self.scrollView addSubview:self.titleLab];
    
    [self.scrollView addSubview:self.contentLab];
    
    [self.contentLab sizeToFit];
    
    [self.scrollView setContentSize:CGSizeMake(0, CGRectGetMaxY(self.contentLab.frame)+100)];
    
}
- (void)customInitialization:(UIView *)view andLeftColorHex:(NSString *)leftHex andRightColorHex:(NSString *)rightHex andCornerRadius:(CGFloat)cornerRadius {
    // 创建并配置CAGradientLayer
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.frame = view.bounds;
    gradientLayer.colors = @[(__bridge id)[UIColor colorWithHexString:rightHex].CGColor,
                             (__bridge id)[UIColor colorWithHexString:leftHex].CGColor];
    gradientLayer.startPoint = CGPointMake(1, 0.3);
    gradientLayer.endPoint = CGPointMake(0.0, 0.3);
    gradientLayer.cornerRadius = cornerRadius;
    // 将CAGradientLayer添加到按钮的图层中
    [view.layer insertSublayer:gradientLayer atIndex:0];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView != self.scrollView) {
        return;
    }
    CGFloat offsetY = scrollView.contentOffset.y;
    
    // 计算透明度范围：[0, 1]之间
    CGFloat alpha = offsetY / 100.0;
    
    // 限制透明度范围为 0 到 1
    if (alpha < 0) {
        alpha = 0;
    } else if (alpha > 1) {
        alpha = 1;
    }
    
    // 更新 navView 的背景颜色透明度
    self.navView.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:alpha];
    self.navTitleLab.textColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:alpha];

}

#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    // 假设返回 20 个项
    return self.dataArr.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    TLRechargeCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TLRechargeCollectionViewCell" forIndexPath:indexPath];
    
    if (self.dataArr.count>indexPath.row) {
        cell.model = self.dataArr[indexPath.row];
    }
    
    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    TLRechargeGoodsModel *model = self.dataArr[indexPath.row];
    
    if (!self.selectedModel) {
        
        model.tl_isSelected = YES;
        self.selectedModel = model;
        
    }else if(self.selectedModel != model){
        
        self.selectedModel.tl_isSelected = NO;
        model.tl_isSelected = YES;
        self.selectedModel = model;
        
    }else if(self.selectedModel == model){
        
        model.tl_isSelected = YES;
        self.selectedModel = model;
        
    }
    
    self.priceLab.text = [NSString stringWithFormat:@"$ %.2f",self.selectedModel.price.floatValue];
    
    [self.priceLab sizeToFit];
    
    [_collectionView reloadData];
}
- (void)netWork{
    
    
    [APIManager sendGetRequest:[APIURLManager getOsGoodsList] parameters:@{@"isVip":@"1"} model:nil success:^(BOOL success, id  _Nullable responseData, APIResponse * _Nonnull requestModel) {
        
        if (success) {
            
            NSArray *data = [TLRechargeGoodsModel mj_objectArrayWithKeyValuesArray:requestModel.data];
            
            [self.dataArr addObjectsFromArray:data];
            
            int x = (int)data.count / 2;
            int y = (int)data.count % 2;
            
            self.goodsView.frame = CGRectMake(0, CGRectGetMaxY(self.headView.frame), kScreenWidth, 140*(x+y));
            
            [self setupUITwo];
            [_collectionView reloadData];
            
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        NSLog(@"%@",error);
    }];
}
- (void)restoreAction{
    NSLog(@"restoreAction");
    
    if (!TL_UserInfoManager.isLogin) {
        
        [TL_LoginViewController presentLoginView:^(TL_UserInfoModel * _Nonnull userDataModel) {
            [self refreshUI];
        }];
        
        return;
    }
    
    
    
    DJAppRestorAlterView *alterView = [DJAppRestorAlterView createViewWithType:@"1"];
    
    [alterView showAction];
    
}
- (void)refreshUI{
    if (TL_UserInfoManager.userInfo.userVip.intValue != 0) {
        _headExLab.text = @"Expiration date：";
        _headExDateLab.text = [NSString stringWithFormat:@"%@", [NSDate convert2LocalTimeWithString:TL_UserInfoManager.userInfo.validUntil andWithFormatter:@"yyyy-MM-dd"]];
    }else{
        _headExLab.text = @"You are not a member yet";
        _headExDateLab.text = @"";
    }
}
@end
